import modelExtend from 'dva-model-extend';

export const model = {
  reducers: {
    bUpdateState(state, {payload}) {
      return {
        ...state,
        ...payload,
      }
    },
  },
};

export const pageModel = modelExtend(model, {
  state: {
    item: {},
    list: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      pageSizeOptions: ['10', '20', '50', '100'],
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
    },
    params: {},		// just for reload
  },

  effects: {
    * bGetPage({payload}, {call, put}) {
      // *scend => *sc
      payload.params.order = payload.params.order === 'ascend' ? 'asc' : 'desc';
      const result = yield call(payload.getPage, payload.params);
      if (result && result.code === 0) {
        yield put({
          type: 'bGetPageSuccess',
          payload: {
            list: result.data.list,
            pagination: {
              current: payload.params && Number(payload.params.page) || 1,
              pageSize: payload.params && Number(payload.params.per_page) || 10,
              total: result.data.total,
            },
            params: payload.params,
          },
        });
      }
    },
  },

  reducers: {
    bSave(state, {payload}) {
      return {
        ...state,
        ...payload,
      };
    },

    bGetAllSuccess(state, {payload}) {
      return {
        ...state,
        list: payload,
      };
    },

    bGetPageSuccess(state, {payload}) {
      const {list, pagination, params} = payload;
      return {
        ...state,
        list,
        pagination: {
          ...state.pagination,
          ...pagination,
        },
        params,
      };
    },

    bSaveItem(state, {payload}) {
      return {
        ...state,
        item: payload,
      };
    },

    bUpdateList(state, {payload}) {
      state.list = state.list.map(item => {
        if (item.id === payload.id) {
          return Object.assign({}, item, payload);
        }
        return item;
      });
      return {
        ...state,
      };
    },
  },
});
